//
//  RBVideoControlsView.m
//  RBVideoPlayer
//
//  Created by Lan on 2017/8/4.
//  Copyright © 2017年 SummerTea. All rights reserved.
//

#import "RBVideoControlsView.h"

@interface RBVideoControlsView ()

@property(nonatomic, assign) CGFloat barHeight;
@property(nonatomic, assign) CGFloat animationDuration;

@property(nonatomic, assign) CGPoint swipeBeginPoint;
@property(nonatomic, assign) RBVideoSwipeDirection swipeDirection;

@property(nonatomic, assign) BOOL locked;

@end

@implementation RBVideoControlsView

#pragma mark - System

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        self.clipsToBounds = YES;
        self.barHeight = 44;
        self.animationDuration = 0.1;
        
        self.tipView.hidden = NO;
        self.gesResponseView.hidden = NO;
        self.fullScreenBtn.hidden = NO;
        
        self.topBar.hidden = NO;
        self.backBtn.hidden = NO;
        self.titleLabel.hidden = NO;
        
        self.bottomBar.hidden = NO;
        self.playBtn.hidden = NO;
        self.currentTimeLabel.hidden = NO;
        self.slider.hidden = NO;
        self.durationLabel.hidden = NO;
        self.fullScreenBtn.hidden = NO;
        
        self.fullScreenProgressView.hidden = YES;
        self.lockScreenBtn.hidden = NO;
        
    }
    return self;
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    if (CGSizeEqualToSize(self.frame.size, self.tipView.frame.size))
    {
        return;
    }
    CGFloat width = CGRectGetWidth(self.frame);
    CGFloat height = CGRectGetHeight(self.frame);
    CGFloat statusBarHeight = [UIApplication sharedApplication].statusBarFrame.size.height;
    CGRect frame;
    CGFloat x, y , w, h;
    self.tipView.frame = self.bounds;
    self.indicatorView.frame = self.tipView.bounds;
    BOOL fullScreen = [self fullScreen];
    self.topBar.frame = ({
        x = 0;
        if (fullScreen)
        {
            h = self.barHeight + statusBarHeight;
        }
        else
        {
            h = self.barHeight;
        }
        y = 0;
        w = width;
        frame = CGRectMake(x, y, w, h);
    });
    self.backBtn.frame = ({
        w = 60;
        h = self.barHeight;
        x = 0;
        y = fullScreen? statusBarHeight: 0;
        frame = CGRectMake(x, y, w, h);
    });
    self.rateBtn.frame = ({
        h = self.barHeight;
        w = h;
        x = width - w;
        y = fullScreen? statusBarHeight: 0;
        frame = CGRectMake(x, y, w, h);
    });
    self.titleLabel.frame = ({
        x = CGRectGetMaxX(self.backBtn.frame);
        y = fullScreen? statusBarHeight: 0;
        w = CGRectGetWidth(self.topBar.frame) - x * 2;
        h = self.barHeight;
        frame = CGRectMake(x, y, w, h);
    });
    self.bottomBar.frame = ({
        x = 0;
        y = height - self.barHeight;
        w = width;
        h = self.barHeight;
        frame = CGRectMake(x, y, w, h);
    });
    self.playBtn.frame = ({
        x = 0;
        y = 0;
        w = CGRectGetHeight(self.bottomBar.frame);
        h = w;
        frame = CGRectMake(x, y, w, h);
    });
    self.fullScreenBtn.frame = ({
        h = CGRectGetHeight(self.bottomBar.frame);
        w = h;
        x = CGRectGetMaxX(self.bottomBar.frame) - w;
        y = 0;
        frame = CGRectMake(x, y, w, h);
    });
    self.slider.frame = ({
        x = CGRectGetMaxX(self.playBtn.frame) + 5;
        h = 30;
        y = 0;
        w = CGRectGetMinX(self.fullScreenBtn.frame) - CGRectGetMaxX(self.playBtn.frame) - 10;
        frame = CGRectMake(x, y, w, h);
    });
    self.currentTimeLabel.frame = ({
        x = CGRectGetMinX(self.slider.frame) + 5;;
        y = CGRectGetMaxY(self.slider.frame) - 8;
        w = 120;
        h = 15;
        frame = CGRectMake(x, y, w, h);
    });
    self.durationLabel.frame = ({
        w = 120;
        h = CGRectGetHeight(self.currentTimeLabel.frame);
        x = CGRectGetMaxX(self.slider.frame) - w - 5;
        y = CGRectGetMinY(self.currentTimeLabel.frame);
        frame = CGRectMake(x, y, w, h);
    });
    self.fullScreenProgressView.frame = ({
        w = width;
        h = 2.5;
        x = 0;
        y = height - h;
        frame = CGRectMake(x, y, w, h);
    });
    [self resizeResponseView];
    self.lockScreenBtn.frame = ({
        CGFloat w = 40;
        CGFloat h = w;
        CGFloat x = 10;
        CGFloat y = self.frame.size.height/2 - h/2;
        CGRectMake(x, y, w, h);
    });
}

#pragma mark - Private

- (void)resizeResponseView
{
    CGFloat x, y, w, h;
    CGRect frame;
    self.gesResponseView.frame = ({
        w = CGRectGetWidth(self.frame);
        x = 0;
        y = !self.topBar.hidden? CGRectGetMaxY(self.topBar.frame): 0;
        h = CGRectGetHeight(self.frame) - y - (CGRectGetHeight(self.frame) - CGRectGetMinY(self.bottomBar.frame));
        frame = CGRectMake(x, y, w, h);
    });
}

#pragma mark - Event

- (void)singleTapGesture: (UITapGestureRecognizer *)gesture
{
    if (self.locked)
    {
        self.lockScreenBtn.hidden = !self.lockScreenBtn.hidden;
        return;
    }
    self.userInteractionEnabled = NO;
    if (self.topBar.frame.origin.y >= 0)
    {
        [UIView animateWithDuration:self.animationDuration animations:^{
            self.topBar.frame = ({
                CGRect frame = self.topBar.frame;
                frame.origin.y = -self.topBar.frame.size.height;
                frame;
            });
            self.bottomBar.frame = ({
                CGRect frame = self.bottomBar.frame;
                frame.origin.y = self.frame.size.height;
                frame;
            });
        } completion:^(BOOL finished) {
            self.userInteractionEnabled = YES;
            [self resizeResponseView];
            [self layoutSubviews];
            self.fullScreenProgressView.hidden = NO;
        }];
    }
    else
    {
        [UIView animateWithDuration:self.animationDuration animations:^{
            self.topBar.frame = ({
                CGRect frame = self.topBar.frame;
                frame.origin.y = 0;
                frame;
            });
            self.bottomBar.frame = ({
                CGRect frame = self.bottomBar.frame;
                frame.origin.y = self.frame.size.height - self.bottomBar.frame.size.height;
                frame;
            });
        } completion:^(BOOL finished) {
            self.userInteractionEnabled = YES;
            [self resizeResponseView];
            [self layoutSubviews];
            self.fullScreenProgressView.hidden = YES;
        }];
    }
}

- (void)doubleTapGesture: (UITapGestureRecognizer *)gesture
{
    if (self.locked)
    {
        return;
    }
    if (self.doubleTapBlock)
    {
        self.doubleTapBlock();
    }
}

- (void)swipeEvent: (UIPanGestureRecognizer *)ges
{
    if (self.locked)
    {
        return;
    }
    CGPoint point = [ges locationInView:self.gesResponseView];
    switch (ges.state) {
        case UIGestureRecognizerStateBegan:
        {
            self.swipeBeginPoint = point;
            self.swipeDirection = 0;
        }
            break;
        case UIGestureRecognizerStateChanged:
        {
            CGFloat xChange = point.x - self.swipeBeginPoint.x;
            CGFloat yChange = point.y - self.swipeBeginPoint.y;
            if (self.swipeDirection == 0)
            {
                if (self.swipeBeginPoint.x > self.gesResponseView.frame.size.width/2 && ABS(yChange)*2 > ABS(xChange))
                {
                    self.swipeDirection = RBVideoSwipeDirectionRightVer;
                }
                else if (self.swipeBeginPoint.x < self.gesResponseView.frame.size.width/2 && ABS(yChange)*2 > ABS(xChange))
                {
                    self.swipeDirection = RBVideoSwipeDirectionLeftVer;
                }
                else
                {
                    self.swipeDirection = RBVideoSwipeDirectionHor;
                }
            }
            if (self.swipeBlock)
            {
                if (self.swipeDirection == RBVideoSwipeDirectionHor)
                {
                    self.swipeBlock(self.swipeDirection, xChange/self.gesResponseView.frame.size.width, NO);
                }
                else
                {
                    self.swipeBlock(self.swipeDirection, -yChange/self.gesResponseView.frame.size.height, NO);
                }
            }
        }
            break;
        case UIGestureRecognizerStateEnded:
        {
            self.swipeBlock(self.swipeDirection, 0, YES);
        }
            break;
        default:
            break;
    }
}

- (void)lockBtnTapped
{
    self.locked = !self.locked;
}

#pragma mark - Setter

- (void)setPlaying:(BOOL)playing
{
    _playing = playing;
    if (!playing)
    {
        [self.playBtn setImage:[UIImage imageNamed:@"RBMediaPlayer.bundle/play"] forState:UIControlStateNormal];
    }
    else
    {
        [self.playBtn setImage:[UIImage imageNamed:@"RBMediaPlayer.bundle/pause"] forState:UIControlStateNormal];
    }
}

- (void)setLocked:(BOOL)locked
{
    _locked = locked;
    [self.lockScreenBtn setImage:[UIImage imageNamed:locked? @"RBMediaPlayer.bundle/lock": @"RBMediaPlayer.bundle/unlock"] forState:UIControlStateNormal];
    self.topBar.alpha = locked? 0: 1;
    self.bottomBar.alpha = locked? 0: 1;
    if (locked)
    {
        self.fullScreenProgressView.hidden = NO;
    }
    else
    {
        if (self.bottomBar.frame.origin.y < self.frame.size.height)
        {
            self.fullScreenProgressView.hidden = YES;
        }
        else
        {
            self.fullScreenProgressView.hidden = NO;
        }
    }
}

#pragma mark - Getter

- (BOOL)fullScreen
{
    return CGRectGetWidth(self.frame) > MIN([UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height) + 10;
}

- (UIView *)topBar
{
    if (!_topBar)
    {
        self.topBar = ({
            UIView *view = [UIView new];
            view.backgroundColor = [UIColor colorWithWhite:0 alpha:0.4];
            [self addSubview:view];
            view;
        });
    }
    return _topBar;
}

- (UIButton *)backBtn
{
    if (!_backBtn)
    {
        self.backBtn = ({
            UIButton *view = [UIButton new];
            view.adjustsImageWhenHighlighted = NO;
            view.showsTouchWhenHighlighted = YES;
            [view setImage:[UIImage imageNamed:@"RBMediaPlayer.bundle/backArror"] forState:UIControlStateNormal];
            CGFloat arrorHeight = 20;
            CGFloat arrorWidth = arrorHeight * 21 / 36;
            view.imageEdgeInsets = UIEdgeInsetsMake(10, 10, 10, 50 - arrorWidth);
            [self.topBar addSubview:view];
            view;
        });
    }
    return _backBtn;
}

- (UIButton *)rateBtn
{
    if (!_rateBtn)
    {
        self.rateBtn = ({
            UIButton *view = [UIButton new];
            [view setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            [view setTitle:@"1X" forState:UIControlStateNormal];
            view.titleLabel.font = [UIFont systemFontOfSize:13];
            [self.topBar addSubview:view];
            view;
        });
    }
    return _rateBtn;
}

- (UILabel *)titleLabel
{
    if (!_titleLabel)
    {
        self.titleLabel = ({
            UILabel *view = [UILabel new];
            view.textAlignment = NSTextAlignmentCenter;
            view.textColor = [UIColor whiteColor];
            view.font = [UIFont systemFontOfSize:15];
            view.text = @"--";
            [self.topBar addSubview:view];
            view;
        });
    }
    return _titleLabel;
}

- (UIView *)bottomBar
{
    if (!_bottomBar)
    {
        self.bottomBar = ({
            UIView *view = [UIView new];
            view.backgroundColor = self.topBar.backgroundColor;
            [self addSubview:view];
            view;
        });
    }
    return _bottomBar;
}

- (UIButton *)playBtn
{
    if (!_playBtn)
    {
        self.playBtn = ({
            UIButton *view = [UIButton new];
            view.showsTouchWhenHighlighted = YES;
            view.imageEdgeInsets = UIEdgeInsetsMake(10, 10, 10, 10);
            view.adjustsImageWhenHighlighted = NO;
            [view setImage:[UIImage imageNamed:@"kr-video-player-play"] forState:UIControlStateNormal];
            [self.bottomBar addSubview:view];
            view;
        });
    }
    return _playBtn;
}

- (UIButton *)fullScreenBtn
{
    if (!_fullScreenBtn)
    {
        self.fullScreenBtn = ({
            UIButton *view = [UIButton new];
            view.showsTouchWhenHighlighted = YES;
            view.imageEdgeInsets = UIEdgeInsetsMake(10, 10, 10, 10);
            view.adjustsImageWhenHighlighted = NO;
            [view setImage:[UIImage imageNamed:@"RBMediaPlayer.bundle/fullscreen"] forState:UIControlStateNormal];
            [self.bottomBar addSubview:view];
            view;
        });
    }
    return _fullScreenBtn;
}

- (RBMediaSlider *)slider
{
    if (!_slider)
    {
        self.slider = ({
            RBMediaSlider *view = [RBMediaSlider new];
            __weak typeof(self) weak_self = self;
            view.playProgressChangedBlock = ^(CGFloat playProgress) {
                weak_self.fullScreenProgressView.progress = playProgress;
            };
            [self.bottomBar addSubview:view];
            view;
        });
    }
    return _slider;
}

- (UILabel *)currentTimeLabel
{
    if (!_currentTimeLabel)
    {
        self.currentTimeLabel = ({
            UILabel *view = [UILabel new];
            view.text = @"00:00";
            view.textColor = [UIColor whiteColor];
            view.font = [UIFont systemFontOfSize:12];
            [self.bottomBar addSubview:view];
            view;
        });
    }
    return _currentTimeLabel;
}

- (UILabel *)durationLabel
{
    if (!_durationLabel)
    {
        self.durationLabel = ({
            UILabel *view = [UILabel new];
            view.textAlignment = NSTextAlignmentRight;
            view.text = @"00:00";
            view.textColor = self.currentTimeLabel.textColor;
            view.font = self.currentTimeLabel.font;
            [self.bottomBar addSubview:view];
            view;
        });
    }
    return _durationLabel;
}

- (UIButton *)lockScreenBtn
{
    if (!_lockScreenBtn)
    {
        self.lockScreenBtn = ({
            UIButton *view = [UIButton new];
            view.imageEdgeInsets = UIEdgeInsetsMake(10, 10, 10, 10);
            view.adjustsImageWhenHighlighted = NO;
            [view setImage:[UIImage imageNamed:@"RBMediaPlayer.bundle/unlock"] forState:UIControlStateNormal];
            [view addTarget:self action:@selector(lockBtnTapped) forControlEvents:UIControlEventTouchUpInside];
            [self addSubview:view];
            view;

        });
    }
    return _lockScreenBtn;
}

- (UIProgressView *)fullScreenProgressView
{
    if (!_fullScreenProgressView)
    {
        self.fullScreenProgressView = ({
            UIProgressView *view = [UIProgressView new];
            view.trackTintColor = [UIColor colorWithWhite:0 alpha:0.4];
            view.progressTintColor = [UIColor colorWithRed:0.7 green:0.25 blue:0.25 alpha:1];
            [self addSubview:view];
            view;
        });
    }
    return _fullScreenProgressView;
}

- (UILabel *)tipView
{
    if (!_tipView)
    {
        self.tipView = ({
            UILabel *view = [UILabel new];
            view.textColor = [UIColor whiteColor];
            view.font = [UIFont systemFontOfSize:13];
            view.numberOfLines = 0;
            view.textAlignment = NSTextAlignmentCenter;
            [self addSubview:view];
            view;
        });
    }
    return _tipView;
}

- (UIActivityIndicatorView *)indicatorView
{
    if (!_indicatorView)
    {
        self.indicatorView = ({
            UIActivityIndicatorView *view = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
            [self.tipView addSubview:view];
            view;
        });
    }
    return _indicatorView;
}

- (UIView *)gesResponseView
{
    if (!_gesResponseView)
    {
        self.gesResponseView = ({
            UIView *view = [UIView new];
            
            UITapGestureRecognizer *singleTapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(singleTapGesture:)];
            [view addGestureRecognizer:singleTapGesture];
            
            UITapGestureRecognizer *doubleTapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(doubleTapGesture:)];
            doubleTapGesture.numberOfTapsRequired = 2;
            [view addGestureRecognizer:doubleTapGesture];
            [singleTapGesture requireGestureRecognizerToFail:doubleTapGesture];
            
            UIPanGestureRecognizer *swipeGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(swipeEvent:)];
            [view addGestureRecognizer:swipeGesture];
            
            [self addSubview:view];
            view;
        });
    }
    return _gesResponseView;
}

@end
